// 引入存储工具
const storage = require('../../utils/storage.js');

Page({
    data: {
        tabList: [
            { title: '首页' },
            { title: '活动列表' },
            { title: '我的' }
        ],
        activityRows: [] ,  // 二维数组，每行 2 个活动
        currentTab: 0,
        // 轮播图图片路径数组
        bannerList: [
            'https://vcg03.cfp.cn/creative/vcg/800/new/VCG211305050246.jpg',
            'https://vcg00.cfp.cn/creative/vcg/800/new/VCG211320993728.jpg',
            'https://vcg01.cfp.cn/creative/vcg/800/new/VCG211428489532.jpg',
        ],
        activityList: [
            {
                id: 1,
                imageUrl: 'https://ts1.tc.mm.bing.net/th/id/R-C.5f7fe8e7260e19bba467e9aa84f16f74?rik=Wy1Cr2EKAEW4JQ&riu=http%3a%2f%2fe0.ifengimg.com%2f09%2f2019%2f0705%2f24E11383BCD35A48FE0B9C0D75C32F37B72596B6_size131_w1280_h960.jpeg&ehk=CtB6imO98G3bf0%2bMcL1aI8Ale4%2f5y8mawFbklxqH7sk%3d&risl=&pid=ImgRaw&r=0',
                title: '舞蹈篇｜社区广场舞晨练队｜多人参与',
                tags: '活动',
                isRegistered: false
            },
            {
                id: 2,
                imageUrl: 'https://ts4.tc.mm.bing.net/th/id/OIP-C.rgy7bwzqp5uohgDqLeTf1QHaE8?rs=1&pid=ImgDetMain&o=7&rm=3',
                title: '书法交流｜邻里书法交流会｜多人参与',
                tags: '文化',
                isRegistered: false
            },
            {
                id: 3,
                title: '户外徒步｜社区健步走俱乐部｜多人参与',
                imageUrl: 'https://ts4.tc.mm.bing.net/th/id/OIP-C.-C0pTRQf8zyVE5AnQRbllQAAAA?rs=1&pid=ImgDetMain&o=7&rm=3',
                tags: '运动',
                isRegistered: false
            }
        ]
    },
    switchTab(e) {
        const index = e.currentTarget.dataset.index;
        this.setData({
            currentTab: index
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    goTocreate() {
        wx.navigateTo({
            url: '/pages/create-activity/create-activity',
        })
    
    },
    goTomyactivities(){
        wx.navigateTo({
            url: '/pages/myactivities/myactivities',
        })
    },
    goTomycreate() {
        wx.navigateTo({
            url: '/pages/create-activity/mycreate',
        })
    
    },
    
    onLoad(options) {
        // 原始一维数据
    const list = [
        {
          id: 1,
          title: '社区健步走',
          time: '今天 07:30-08:30',
          address: '东湖公园北门',
          tags: ['免费', '户外'],
          cover: 'https://n.sinaimg.cn/sinakd20220815s/381/w708h473/20220815/a95b-9a950697be3a633fa318f9762b948032.jpg',
          qr: '/images/coin.png'
        },
        {
          id: 2,
          title: '智能手机课堂',
          time: '本周五 09:30-11:00',
          address: '社区二楼教室',
          tags: ['公益', '教学'],
          cover: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.w-NaiTklvOKi_94okOXq9wHaFj?w=252&h=189&c=7&r=0&o=5&dpr=2&pid=1.7',
          qr: '/images/coll.png'
        },
        {
            id: 3,
            title: '社区健步走',
            time: '今天 07:30-08:30',
            address: '东湖公园北门',
            tags: ['免费', '户外'],
            cover: 'https://n.sinaimg.cn/sinakd20220815s/381/w708h473/20220815/a95b-9a950697be3a633fa318f9762b948032.jpg',
            qr: '/images/coin.png'
          },
          {
            id: 4,
            title: '智能手机课堂',
            time: '本周五 09:30-11:00',
            address: '社区二楼教室',
            tags: ['公益', '教学'],
            cover: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.w-NaiTklvOKi_94okOXq9wHaFj?w=252&h=189&c=7&r=0&o=5&dpr=2&pid=1.7',
            qr: '/images/coll.png'
          }
        // …可以继续加
      ];
  
      // 切成二维：[[第1个,第2个], [第3个,第4个], …]
      const rows = [];
      for (let i = 0; i < list.length; i += 2) {
        rows.push(list.slice(i, i + 2));
      }
      this.setData({ activityRows: rows });
    

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    // 活动报名处理
    handleRegistration(e) {
        const { id, title, cover, imageUrl, tags, time, address } = e.currentTarget.dataset;
        
        // 创建活动数据对象，兼容不同来源的数据格式
        const activity = {
            id: Number(id),
            title,
            imageUrl: imageUrl || cover,
            tags: Array.isArray(tags) ? tags.join(',') : tags,
            time: time || '',
            address: address || '',
            registrationTime: new Date().getTime()
        };
        
        // 获取已报名活动
        let registeredActivities = wx.getStorageSync('REGISTERED_ACTIVITIES') || [];
        
        // 检查是否已报名
        const isRegistered = registeredActivities.some(item => item.id === activity.id);
        
        if (isRegistered) {
            wx.showToast({
                title: '您已报名该活动',
                icon: 'none'
            });
            return;
        }
        
        // 添加新报名活动
        registeredActivities.push(activity);
        
        // 保存到本地存储
        wx.setStorageSync('REGISTERED_ACTIVITIES', registeredActivities);
        
        // 更新页面状态
        this.loadRegisteredActivities();
        
        // 提示成功
        wx.showToast({
            title: '报名成功',
            icon: 'success'
        });
    },
    
    // 加载已报名活动状态
    loadRegisteredActivities() {
        // 获取已报名活动
        const registeredActivities = wx.getStorageSync('REGISTERED_ACTIVITIES') || [];
        const registeredIds = registeredActivities.map(activity => activity.id);
        
        // 更新首页活动的报名状态
        let updatedActivityRows = JSON.parse(JSON.stringify(this.data.activityRows));
        updatedActivityRows.forEach(row => {
            row.forEach(act => {
                act.isRegistered = registeredIds.includes(Number(act.id));
            });
        });
        
        // 更新活动列表的报名状态
        let updatedActivityList = JSON.parse(JSON.stringify(this.data.activityList));
        updatedActivityList.forEach(item => {
            item.isRegistered = registeredIds.includes(Number(item.id));
        });
        
        this.setData({
            activityRows: updatedActivityRows,
            activityList: updatedActivityList
        });
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.loadRegisteredActivities();
    },

    // 加载已报名活动状态
    loadRegisteredActivities() {
        // 获取已报名活动
        const registeredActivities = wx.getStorageSync('REGISTERED_ACTIVITIES') || [];
        const registeredIds = registeredActivities.map(activity => activity.id);
        
        // 更新首页活动的报名状态
        let updatedActivityRows = JSON.parse(JSON.stringify(this.data.activityRows));
        updatedActivityRows.forEach(row => {
            row.forEach(act => {
                act.isRegistered = registeredIds.includes(Number(act.id));
            });
        });
        
        // 更新活动列表的报名状态
        let updatedActivityList = JSON.parse(JSON.stringify(this.data.activityList));
        updatedActivityList.forEach(item => {
            item.isRegistered = registeredIds.includes(Number(item.id));
        });
        
        this.setData({
            activityRows: updatedActivityRows,
            activityList: updatedActivityList
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})